<?php

abstract class CompilerBase {

    protected $targetFilePath;
    protected $outputFilePath;
    protected $requestModel;
    protected $compileOutput;
    protected $compileReturnValue;
    protected $executionScriptPath;
    protected $gradingDirectory;

    public function __construct($request) {
        $this->targetFilePath = "";
        $this->requestModel = $request;
        //$this->requestModel->dispatch_time = new CDbExpression("NOW()");
        $this->requestModel->dispatch_time = date("Y-m-d H:i:s");
        $this->requestModel->save();
    }

    protected abstract function beforeCompile();

    protected abstract function afterCompile();

    protected abstract function doCompile();
    
    protected abstract function generateExecutionScript();
    
    public abstract function setTarget($target);
    
    private function prepareGradingDirectory() {
        $this->gradingDirectory = Yii::app()->params['config']['compiler']['temp_dir'] . "/" . $this->requestModel->id;
        
        if (!file_exists($this->gradingDirectory))
            mkdir($this->gradingDirectory);
    }

    public final function compile() {
        $this->prepareGradingDirectory();
        
        $this->beforeCompile();

        ///Init
        $this->compileOutput = "";
        $this->compileReturnValue = -1;
        $this->outputFilePath = "";

        $this->doCompile();
        $this->generateExecutionScript();
        $this->afterCompile();
    }
    
    public final function getGradingDirectory() {
        return $this->gradingDirectory;
    }

    public final function getOutputFilePath() {
        return $this->outputFilePath;
    }

    public final function getCompileOutput() {
        return $this->compileOutput;
    }

    public final function getCompileReturnValue() {
        return $this->compileReturnValue;
    }
    
    public final function getExecutionScriptPath() {
        return $this->executionScriptPath;
    }
    
    public final function getRequestModel() {
        return $this->requestModel;
    }
    
    public function cleanup() {
        /*if (file_exists($this->outputFilePath))
            unlink ($this->outputFilePath);*/
        
        if (file_exists($this->gradingDirectory))
            exec("rm -rf " . $this->gradingDirectory);
    }

}

?>
